package com.ebt.m.view;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.event.SwitchBottomTabEvent;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.TalkingDataUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * @author andy.wang
 */
public class BottomBar extends LinearLayout {


    private Context mContext;
    private Paint paint;


    //左右布局宽度
    private int contentWidth;

    //选项卡
    private List<SpaceItem> spaceItems = new ArrayList<>();

    //选项卡View
    private List<ViewGroup> spaceItemList = new ArrayList<>();

    //存放左边选项卡内容
    private LinearLayout leftContent;
    //存放右边选项卡内容
    private LinearLayout rightContent;
    private RelativeLayout centerContent;
    //中间原型按钮
    private ImageButton centerButton;

    //左右分割标志
    private int flag;

    //当前选中的选卡序号
    private int selected = 0;
    /**
     * 自定义属性
     */
    private boolean isBorder; //是否需要上边框
    private float borderSize;//边框大小
    private
    @ColorInt
    int borderColor;//边框颜色
    private
    @ColorInt
    int spaceColor;//控件背景
    private
    @ColorInt
    int centerButtonColor;//中间按钮颜色
    private
    @DrawableRes
    int centreButtonIcon;//中间按钮图标
    private int centreButtonSize;//中间圆形按钮大小
    private
    @ColorInt
    int centerButtonImgColor;//中间按钮图标颜色
    private
    @ColorInt
    int selectItemColor;//选中是的颜色
    private
    @ColorInt
    int unSelectItemColor;//未选中的颜色
    private float itemTextSize;//字体大小
    private int itemImgSize;//图标大小


    //点击时间接口
    private OnItemClickClickListener onItemClickClickListener;


    public BottomBar(Context context) {
        super(context);
        mContext = context;
        paint = new Paint();
    }

    public BottomBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        Resources resources = getResources();
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BottomBar);
        isBorder = typedArray.getBoolean(R.styleable.BottomBar_is_border, false);
        borderSize = typedArray.getDimension(R.styleable.BottomBar_border_size, 1f);
        borderColor = typedArray.getColor(R.styleable.BottomBar_bordercolor, ContextCompat.getColor(context, R.color.default_inactive_item_color));
        spaceColor = typedArray.getColor(R.styleable.BottomBar_space_color, ContextCompat.getColor(context, R.color.space_white));
        centerButtonColor = typedArray.getColor(R.styleable.BottomBar_center_button_color, ContextCompat.getColor(context, R.color.centre_button_color));
        centreButtonIcon = typedArray.getResourceId(R.styleable.BottomBar_center_button_icon, R.drawable.bottom4add);
        centreButtonSize = (int) typedArray.getDimension(R.styleable.BottomBar_centre_button_size, resources.getDimension(R.dimen.centre_button_default_size));
        centerButtonImgColor = typedArray.getColor(R.styleable.BottomBar_center_button_img_color, ContextCompat.getColor(context, R.color.space_white));
        selectItemColor = typedArray.getColor(R.styleable.BottomBar_select_item_color, ContextCompat.getColor(context, R.color.default_active_item_color));
        unSelectItemColor = typedArray.getColor(R.styleable.BottomBar_un_select_item_color, ContextCompat.getColor(context, R.color.default_inactive_item_color));
        itemTextSize = typedArray.getDimension(R.styleable.BottomBar_item_text_size, resources.getDimension(R.dimen.space_item_text_default_size));
        itemImgSize = (int) typedArray.getDimension(R.styleable.BottomBar_item_img_ize, resources.getDimension(R.dimen.space_item_icon_default_size));
        typedArray.recycle();
        mContext = context;
        paint = new Paint();

    }

    public BottomBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        paint = new Paint();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isBorder) {
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            paint.setColor(borderColor);
            paint.setStrokeWidth(borderSize);
            canvas.drawLine(0, 0, getMeasuredWidth(), 0, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setBackgroundColor(spaceColor);
        int wModel = MeasureSpec.getMode(widthMeasureSpec);
        int wSize = MeasureSpec.getSize(widthMeasureSpec);
        int hModel = MeasureSpec.getMode(heightMeasureSpec);
        int hSize = MeasureSpec.getSize(heightMeasureSpec);

        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        if (hModel == MeasureSpec.EXACTLY) {
            layoutParams.height = hSize;
        } else if (wModel == MeasureSpec.AT_MOST) {
            layoutParams.height = Math.min(dip2px(mContext, 60), hSize);
        } else {
            layoutParams.height = dip2px(mContext, 60);
        }

        setLayoutParams(layoutParams);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        contentWidth = (getMeasuredWidth() - centreButtonSize) / 2;
        removeAllViews();
        postRequestLayout();
        initAndAddViewsToMainView();
    }


    /**
     * 初始化控件
     */
    private void initAndAddViewsToMainView() {
        leftContent = new LinearLayout(mContext);
        rightContent = new LinearLayout(mContext);
        centerContent = new RelativeLayout(mContext);

        centerButton = new ImageButton(mContext);
        centerButton.setBackgroundResource(centreButtonIcon);

        centerButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onItemClickClickListener != null)
                    onItemClickClickListener.centerButtonClick(view);

            }
        });

        /**
         * centerButton 布局参数
         */
        RelativeLayout.LayoutParams fabParams = new RelativeLayout.LayoutParams(centreButtonSize, centreButtonSize);
        fabParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        centerContent.addView(centerButton, fabParams);

        /**
         * Center content size
         */

        LayoutParams centerContentParams = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1);


        /**
         * Left content size
         */

        LayoutParams leftContentParams = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 2);


        /**
         * Right content size
         */
        LayoutParams rightContentParams = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 2);



        /**
         * Adding views to mainContent
         */
        addView(leftContent, leftContentParams);
        addView(centerContent, centerContentParams);
        addView(rightContent, rightContentParams);

        /**
         * Adding current space items to left and right content
         */
        addSpaceItems(leftContent, rightContent);
    }


    private void postRequestLayout() {
        BottomBar.this.getHandler().post(new Runnable() {
            @Override
            public void run() {
                BottomBar.this.requestLayout();
            }
        });
    }

    public void addSpaceItem(SpaceItem item) {
        spaceItems.add(item);
    }

    /**
     * 左右布局选项卡填充
     */
    private void addSpaceItems(LinearLayout leftContent, LinearLayout rightContent) {
        int sum = spaceItems.size();

        flag = sum / 2 + sum % 2;//计算左右分割点 如果是奇数左边多一个

        if (leftContent.getChildCount() > 0 || rightContent.getChildCount() > 0) {
            leftContent.removeAllViews();
            rightContent.removeAllViews();
        }


        spaceItemList.clear();


        /**
         * 获取布局加载器
         * */
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        for (int i = 0; i < spaceItems.size(); i++) {
            final int index = i;

            /**
             * 加载选项布局
             * */
            LinearLayout.LayoutParams textAndIconContainerParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
            RelativeLayout textAndIconContainer = (RelativeLayout) inflater.inflate(R.layout.space_item_view, this, false);
            TypedArray array = mContext.obtainStyledAttributes(new int[]{android.R.attr.selectableItemBackgroundBorderless});
            int backResId = array.getResourceId(0, 0);
            if (backResId != 0)
                textAndIconContainer.setBackgroundResource(backResId);
            array.recycle();
            textAndIconContainer.setLayoutParams(textAndIconContainerParams);
            ImageView spaceItemIcon = (ImageView) textAndIconContainer.findViewById(R.id.space_icon);
            TextView spaceItemText = (TextView) textAndIconContainer.findViewById(R.id.space_text);
            spaceItemText.setText(spaceItems.get(i).getText());
            TextView numTv = (TextView) textAndIconContainer.findViewById(R.id.main_bottom_tab_num);

            /**
             * 设置选项卡图标和文字的颜色
             * */
            if (index == selected) {
                spaceItemText.setTextColor(selectItemColor);
                spaceItemIcon.setBackgroundResource(spaceItems.get(i).getSelectedIcon());
                numTv.setBackgroundResource(R.drawable.bg_green_selected);
            } else {
                spaceItemText.setTextColor(unSelectItemColor);
                spaceItemIcon.setBackgroundResource(spaceItems.get(i).getNormalIcon());
                numTv.setBackgroundResource(R.drawable.bg_green_normal);
            }


            /**
             * 把选项的View保存到list中方便点击是处理
             */
            spaceItemList.add(textAndIconContainer);


            /**
             * 根据分割标志flag把选项放到左右布局
             */
            if (leftContent.getChildCount() == flag) {
                rightContent.addView(textAndIconContainer, textAndIconContainerParams);
            } else {
                leftContent.addView(textAndIconContainer, textAndIconContainerParams);
            }

            /**
             * 添加点击事件
             * */
            textAndIconContainer.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View view) {
                    performItemClick(index);

                }
            });
        }

    }

    public void performItemClick(int pos) {
        if (pos != selected) {
            updateItem(pos);
            if (onItemClickClickListener != null) {
                onItemClickClickListener.spaceItemClick(selected, pos, spaceItems.get(pos));
                TalkingDataUtil.onEventWithLabel(TalkingDataUtil.TYPE_BOTTOMBAR, spaceItems.get(pos).getText());
            }
            selected = pos;

        }
    }

    public void updateItemIcon(int index, SpaceItem spaceItem) {
        post(() -> {
            try {
                spaceItems.set(index, spaceItem);
                ImageView newImage = (ImageView) spaceItemList.get(index).getChildAt(0);
                TextView newText = (TextView) spaceItemList.get(index).getChildAt(2);
                if (index == selected) {
                    newImage.setBackgroundResource(spaceItems.get(index).getSelectedIcon());
                    newText.setTextColor(selectItemColor);
                    newText.setText(spaceItems.get(index).getText());
                } else {
                    newImage.setBackgroundResource(spaceItems.get(index).getNormalIcon());
                    newText.setTextColor(unSelectItemColor);
                    newText.setText(spaceItems.get(index).getText());
                }
            } catch (Exception e) {
                Logger.e(e);
            }
        });
    }

    /**
     * 更改选项的颜色
     */
    private void updateItem(int index) {
        ImageView oldImage = (ImageView) spaceItemList.get(selected).getChildAt(0);
        oldImage.setBackgroundResource(spaceItems.get(selected).getNormalIcon());
        TextView oldText = (TextView) spaceItemList.get(selected).getChildAt(2);
        oldText.setTextColor(unSelectItemColor);
        ImageView newImage = (ImageView) spaceItemList.get(index).getChildAt(0);
        newImage.setBackgroundResource(spaceItems.get(index).getSelectedIcon());
        TextView newText = (TextView) spaceItemList.get(index).getChildAt(2);
        newText.setTextColor(selectItemColor);
        TextView oldNum = (TextView) spaceItemList.get(selected).getChildAt(1);
        oldNum.setBackgroundResource(R.drawable.bg_green_normal);
        TextView newNum = (TextView) spaceItemList.get(index).getChildAt(1);
        newNum.setBackgroundResource(R.drawable.bg_green_selected);

    }


    /**
     * 对外的事件接口
     */
    public interface OnItemClickClickListener {
        /**
         * 选项点击事件
         *
         * @param oldIndex  点击前选中的序号
         * @param newIndex  点击后选中的序号
         * @param spaceitem
         */
        void spaceItemClick(int oldIndex, int newIndex, SpaceItem spaceitem);

        /**
         * 中间按钮点击事件
         */
        void centerButtonClick(View view);
    }

    /**
     * 给控件添加事件
     */
    public void setOnItemClickClickListener(OnItemClickClickListener onItemClickClickListener) {
        this.onItemClickClickListener = onItemClickClickListener;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onSwitchTabEvent(SwitchBottomTabEvent event){
        performItemClick(event.pos);
    }
}
